package com.hopu.mvc.controller;

import com.hopu.mvc.entity.Student;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * RestFul风格的控制器
 */
@CrossOrigin
@RestController
public class StudentController {

    List<Student> students = new ArrayList<>();
    {
        students.addAll(
        Arrays.asList(new Student(1,"张三",20,"数学"),
                new Student(2,"张大三",20,"数学"),
                new Student(3,"张小三",20,"数学"),
                new Student(4,"张三三",20,"数学"),
                new Student(5,"张三四",20,"数学"))
        );
    }

    /**
     * 查询多个数据
     * @return
     */
    @GetMapping("/students")
    public ResponseEntity<List<Student>> findAll(){
        //返回多个数据
        return ResponseEntity.ok(students);
    }

    /**
     * 查询单个学生
     * @param id
     * @return
     */
    @GetMapping("/student/{id}")
    public ResponseEntity<Student> findById(@PathVariable("id")Integer id){
        //模拟数据库查询
        Student student = students.stream().filter(stu -> id == stu.getId())
                .collect(Collectors.toList()).get(0);
        return ResponseEntity.ok(student);
    }

    /**
     * 添加学生
     * @return
     */
    @PostMapping("/student")
    public ResponseEntity<Student> addStudent(@RequestBody Student student){
        System.out.println("添加：" + student);
        students.add(student);
        return ResponseEntity.ok(student);
    }

    /**
     * 更新学生
     * @return
     */
    @PutMapping("/student")
    public ResponseEntity<Student> updateStudent(@RequestBody Student student){
        System.out.println("更新：" + student);
        Student stu2 = students.stream().filter(stu -> student.getId() == stu.getId()).collect(Collectors.toList()).get(0);
        stu2 = student;
        return ResponseEntity.ok(student);
    }

    /**
     * 删除学生
     * @return
     */
    @DeleteMapping("/student/{id}")
    public ResponseEntity<Student> deleteStudent(@PathVariable("id")Integer id){
        System.out.println("删除：" + id);
        Student stu2 = students.stream().filter(stu -> id == stu.getId()).collect(Collectors.toList()).get(0);
        students.remove(stu2);
        return ResponseEntity.ok(stu2);
    }
}
